package org.xwalk.core.internal;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class CustomViewCallbackHandlerBridge extends CustomViewCallbackHandlerInternal {
    private XWalkCoreBridge coreBridge;
    private Object wrapper;

    public Object getWrapper() {
        return wrapper;
    }


    private CustomViewCallbackHandlerInternal internal;

    CustomViewCallbackHandlerBridge(CustomViewCallbackHandlerInternal internal) {
        this.internal = internal;
        reflectionInit();
    }

    @Override
    public void onCustomViewHidden() {
        if (onCustomViewHiddenMethod == null || onCustomViewHiddenMethod.isNull()) {
            onCustomViewHiddenSuper();
        } else {
            onCustomViewHiddenMethod.invoke();
        }
    }

    public void onCustomViewHiddenSuper() {
        if (internal == null) {
            super.onCustomViewHidden();
        } else {
            internal.onCustomViewHidden();
        }
    }

    private ReflectMethod onCustomViewHiddenMethod = new ReflectMethod(null, "onCustomViewHidden");


    void reflectionInit() {
        coreBridge = XWalkCoreBridge.getInstance();
        if (coreBridge == null) return;

        ReflectConstructor constructor = new ReflectConstructor(
                coreBridge.getWrapperClass("CustomViewCallbackHandler"), Object.class);
        try {
            wrapper = constructor.newInstance(this);
        } catch (UnsupportedOperationException e) {
            return;
        }

        onCustomViewHiddenMethod.init(wrapper, null,
                "onCustomViewHidden");
    }
}
